import { Directive, inject, OnDestroy } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { AbstractControl } from '@angular/forms';
import { selectIsLoading } from '@core/interceptors/load.selectors';
import { AppState } from '@core/cne.state';
import { Subscription, Observable } from 'rxjs';
import { delay, share } from 'rxjs/operators';

/**
 * 页面组件基类
 * 
 * - 自动管理全局加载状态
 * - 自动禁用/启用表单控件
 */
@Directive()
export abstract class PageComponent implements OnDestroy {
  protected store = inject(Store<AppState>);
  
  // 加载状态 Observable（延迟订阅模式）
  isLoading$: Observable<boolean>;
  
  // 需要在加载时禁用的表单控件数组
  private readonly disabledOnLoadFormControls: AbstractControl[] = [];
  
  // NgRx 状态订阅
  private loadingSubscription?: Subscription;
  
  protected constructor() {
    // 创建 Observable，但不立即订阅（延迟订阅模式）
    this.isLoading$ = this.store.pipe(delay(0), select(selectIsLoading), share());
  }
  /**
   * 注册需要在加载时禁用的表单控件
   * @param control 表单控件
   */
  protected registerDisableOnLoadFormControl(control: AbstractControl): void {
    this.disabledOnLoadFormControls.push(control);
    
    // 只在第一次注册控件时才创建订阅（延迟订阅模式）
    if (!this.loadingSubscription) {
      this.loadingSubscription = this.isLoading$.subscribe((isLoading: boolean) => {
        // 更新表单控件状态
        for (const formControl of this.disabledOnLoadFormControls) {
          if (isLoading) {
            formControl.disable({ emitEvent: false });
          } else {
            formControl.enable({ emitEvent: false });
          }
        }
      });
    }
  }
  
  /**
   * 组件销毁时清理资源
   */
  ngOnDestroy(): void {
    this.loadingSubscription?.unsubscribe();
  }
}
